var empty_list_html = null;
function RequestBranchData(grade) {
    var grade_param = grade ? ('+grade:' + grade) : '';
    var target = document.getElementById('document_list');
    if (!empty_list_html) empty_list_html = target.innerHTML;
    target.innerHTML = empty_list_html;
    RequestLibraryData("documents?q=topic:" + ParentParam("id") + grade_param,
		       function(results, terms) {
			   ProcessBranchData(
			       "document_list", results, terms); });
}

var documents = null;
var page_count = null;
function ProcessBranchData(target, results, terms) {
    var topic_id = ParentParam("id");
    var title = terms["topic:" + topic_id];
    document.getElementById("section_title").innerHTML = title;
    documents = results;
    page_count = Math.floor((documents.length - 1)/ 10) + 1;
    RenderDocuments();
}

function RenderDocuments() {
    var doc_html = '';
    var page_html = '';
    if (documents.length == 0) {
	doc_html = '<p><em>No documents found. Please try another topic.</em></p>';
	page_html = '';
    } else {
	var doc_start = (page_current - 1) * 10;
	var doc_end = doc_start + 10;
	if (doc_end > documents.length) doc_end = documents.length;
	for (var i = doc_start; i < doc_end; ++i) {
	    doc_html += RenderLibraryListing(documents[i]);
	}
	page_html = '<ol>';
	for (var i = 0; i <= (page_count+1); ++i) {
	    var page_class = '';
	    var page_number = i;
	    var page_name = i;
	    switch(i) {
	    case 0:
		page_class = 'previous';
		page_name = 'Previous page';
		if (page_current == 1) continue;
		page_number = page_current - 1;
		break;
	    case page_count + 1:
		page_class = 'next';
		page_name = 'Next page';
		if (page_current == page_count) continue;
		page_number = page_current + 1;
		break;
	    case page_current:
		page_class = 'current';
		break;
	    default:
		break;
	    }
	    page_html += '<li class="' + page_class +
		'"><a href="#" onclick="GoToPage(' + page_number +
		');">' + page_name + '</a></li>';
	}
	page_html += '</ul>'
    }
    document.getElementById('document_list').innerHTML = doc_html;
    document.getElementById('page_numbers').innerHTML = page_html;
    if (gadgets.window) gadgets.window.adjustHeight();
}

function GoToPage(i) {
    page_current = i;
    if (i < 1) page_current = 1;
    if (i > page_count) page_current = page_count;
    RenderDocuments();
}

function HandleGradeChange(select) {
    var option = select.options[select.selectedIndex];
    page_current = 1;
    if (option.value == "all") {
	RequestBranchData();
    } else {
	RequestBranchData(option.value);
    }
}
